<template>
  <div class='sub-category'>
    <div class="container">
      <!-- 面包屑 -->
      <SubBread />
      <!-- 筛选框 -->
      <SubFilter />
      <!-- 测试复选框 -->
      <!-- <XtxCheckbox v-model="isAll"/> -->
         <!-- 结果区域 -->
      <div class="goods-lists">
        <!-- 排序 -->
        <SubSort @sort-change="changefilter" />
        <!-- 列表 -->
        <ul>
          <li v-for="item in goodsList" :key="item.id" >
            <GoodsItem :goods="item" />
          </li>
        </ul>
        <!-- 加载 -->
        <XtxInfiniteLoading :loading="loading" :finished="finished" @infinite="getData" />
      </div>
    </div>
  </div>
</template>

<script>
import SubBread from './components/SubBread.vue'
import SubFilter from './components/SubFliter.vue'
import SubSort from './components/subSort.vue'
import GoodsItem from './components/CategoryGoods.vue'
import { ref, watch } from 'vue'
import { findSubCategoryGoods } from '@/api/category'
import { useRoute } from 'vue-router'
export default {
  name: 'SubCategory',
  components: { SubBread, SubFilter, SubSort, GoodsItem },
  setup () {
    // 1. 基础布局
    // 2. 无限加载组件
    // 3. 动态加载数据且渲染
    // 4. 任何筛选条件变化需要更新列表
    const route = useRoute()

    let loading = ref(false)
    let finished = ref(false)
    let goodsList = ref([])
    // 查询参数,传给后台的参数
    let reqParams = {
      page: 1,
      pageSize: 20
    }
    // 获取数据的函数
    const getData = () => {
      loading.value = true
      reqParams.categoryId = route.params.id
      findSubCategoryGoods(reqParams).then(({ result }) => {
        if (result.items.length) {
          goodsList.value.push(...result.items)
          reqParams.page++
        } else {
          // 加载完毕
          finished.value = true
        }
        // 请求结束
        loading.value = false
      })
    }
    // 切换二级分类重新加载
    watch(() => route.params.id, (newVal) => {
      if (newVal && route.path === ('/category/sub/' + newVal)) {
        goodsList.value = []
        reqParams = {
          page: 1,
          pageSize: 20
        }
        finished.value = false
      }
    })

    // SubSort的方法函数
    const changefilter = (filterSort) => {
      // 合并参数
      reqParams = {...reqParams,filterSort}
      reqParams.page = 1
      goodsList.value = []
      finished.value=false
      console.log(reqParams,'reqParams');
      
    }
    // const changefilter = (filterSort) =>{
    //   console.log(filterSort,'filterSort');
    // }
 

    return { loading, finished, goodsList, getData,changefilter }
  }
}
</script>
<style scoped lang='less'>
.goods-lists {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin:0;
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
 
</style>